<template>
    <el-card>
        <div class="toolbar">
            <el-button type="primary" @click="openDialog()">添加排班</el-button>
        </div>
        <el-table :data="paginatedData" border style="width: 100%">
            <el-table-column prop="schedule_id" label="排班ID" width="80" />
            <el-table-column prop="employee_id" label="员工ID" width="100" />
            <el-table-column prop="employeeName" label="员工姓名" />
            <el-table-column prop="shift_type" label="班次" />
            <el-table-column prop="schedule_date" label="排班日期" />
            <el-table-column prop="created_by" label="创建人" width="100" />
            <el-table-column prop="created_at" label="创建时间" width="180" />
            <el-table-column label="操作" width="180">
                <template #default="scope">
                    <el-button size="small" @click="openDialog(scope.row)">更新</el-button>
                    <el-button size="small" type="danger" @click="handleDelete(scope.row.schedule_id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination v-if="tableData.length > pageSize" :current-page="currentPage" :page-size="pageSize"
            :total="tableData.length" @current-change="handlePageChange"
            layout="prev, pager, next, jumper"></el-pagination>

        <el-dialog :title="dialogTitle" v-model="dialogVisible">
            <el-form :model="form" label-width="100px">
                <el-form-item label="员工ID"><el-input v-model="form.employee_id" /></el-form-item>
                <el-form-item label="员工姓名"><el-input v-model="form.employeeName" /></el-form-item>
                <el-form-item label="班次">
                    <el-select v-model="form.shift_type" placeholder="选择班次">
                        <el-option label="早班" value="早班" />
                        <el-option label="中班" value="中班" />
                        <el-option label="晚班" value="晚班" />
                    </el-select>
                </el-form-item>
                <el-form-item label="排班日期">
                    <el-date-picker v-model="form.schedule_date" type="date" placeholder="选择日期" />
                </el-form-item>
                <el-form-item label="创建人">
                    <el-input v-model="form.created_by" disabled />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSave">保存</el-button>
            </template>
        </el-dialog>
    </el-card>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import axios from 'axios'

interface Schedule {
    schedule_id: number
    employee_id: string
    employeeName: string
    shift_type: string
    schedule_date: string
    created_at: string
    created_by: string
}

const currentUser = 'admin' // TODO: 替换为当前登录用户名变量
const today = new Date()

// 生成假数据
const generateFakeSchedules = (): Schedule[] => {
    const names = ['张三', '李四', '王五', '赵六', '钱七']
    const shifts = ['早班', '中班', '晚班']
    return Array.from({ length: 50 }, (_, i) => ({
        schedule_id: i + 1,
        employee_id: 'EMP' + (1000 + i),
        employeeName: names[i % names.length],
        shift_type: shifts[i % shifts.length],
        schedule_date: new Date(today.getTime() + i * 86400000).toISOString().split('T')[0],
        created_at: new Date(today.getTime() - i * 10000000).toISOString(),
        created_by: 'admin'
    }))
}

const tableData = ref<Schedule[]>(generateFakeSchedules())
const currentPage = ref(1)
const pageSize = ref(10)
const dialogVisible = ref(false)
const dialogTitle = ref('添加排班')
const form = ref<Partial<Schedule>>({})

const paginatedData = computed(() => {
    const start = (currentPage.value - 1) * pageSize.value
    return tableData.value.slice(start, start + pageSize.value)
})

const openDialog = (row?: Schedule) => {
    dialogTitle.value = row ? '编辑排班' : '添加排班'
    if (row) {
        form.value = { ...row }
    } else {
        form.value = {
            employee_id: '',
            employeeName: '',
            shift_type: '',
            schedule_date: '',
            created_by: currentUser,
            created_at: new Date().toISOString()
        }
    }
    dialogVisible.value = true
}

const handleSave = async () => {
    const newData = { ...form.value } as Schedule
    try {
        if (form.value.schedule_id) {
            await axios.put(`/api/schedule/${form.value.schedule_id}`, newData)
            const index = tableData.value.findIndex(item => item.schedule_id === form.value.schedule_id)
            if (index !== -1) tableData.value[index] = newData
        } else {
            const response = await axios.post('/api/schedule', newData)
            const newId = response.data?.schedule_id || Date.now()
            tableData.value.push({ ...newData, schedule_id: newId })
        }
        dialogVisible.value = false
    } catch (err) {
        console.error('保存失败', err)
    }
}

const handleDelete = async (id: number) => {
    try {
        await axios.delete(`/api/schedule/${id}`)
        tableData.value = tableData.value.filter(item => item.schedule_id !== id)
    } catch (err) {
        console.error('删除失败', err)
    }
}

const handlePageChange = (page: number) => {
    currentPage.value = page
}
</script>

<style scoped>
.toolbar {
    margin-bottom: 12px;
}

.el-table {
    border-radius: 12px;
    overflow: hidden;
    background: linear-gradient(to bottom, #f0f4ff, #dde6ff, #d1e0ff);
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

.el-table th {
    background-color: rgba(255, 255, 255, 0.6);
    font-weight: bold;
    color: #3a3a3a;
    text-align: center;
}

.el-table td {
    background-color: rgba(255, 255, 255, 0.4);
    color: #333;
    text-align: center;
}

.el-table__row:hover td {
    background-color: rgba(173, 191, 255, 0.4);
    transition: background-color 0.3s ease;
}

.el-table::before {
    background-color: transparent;
}
</style>
